﻿using System;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Controls;
using Pfz.DataTypes;
using Pfz.Factoring;

namespace Pfz.WpfControls.ValueControls
{
	/// <summary>
	/// Control used to represent a date.
	/// </summary>
	[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")]
	[AutoRegisterInControlFactory(typeof(Date))]
	[AutoRegisterInControlFactory(typeof(Date?))]
	internal sealed class DateControl:
		UserControl,
		IValueControl
	{
        private DatePicker _datePicker;
		
		/// <summary>
		/// Creates a new instance of the DateControl.
		/// </summary>
		public DateControl()
		{
            var datePicker = new DatePicker();
            _datePicker = datePicker;
			Content = datePicker;
		}

		/// <summary>
		/// Gets or sets the value as a nullable Date.
		/// </summary>
		public Date? Value
		{
			get
			{
                DateTime? dateTime = _datePicker.SelectedDate;

                if (dateTime.HasValue)
                    return (Date)dateTime.Value;

                return null;
			}
			set
			{
				if (value.HasValue && value.Value != default(Date))
					_datePicker.SelectedDate = value;
				else
					_datePicker.SelectedDate = null;
			}
		}
		
		#region IValueContainer Members
			object IValueContainer.Value
			{
				get
				{
					return Value;
				}
				set
				{
					Value = (Date?)value;
				}
			}
		#endregion

		#region IReadOnlyMakeable Members
			/// <summary>
			/// Clears all the text-boxes.
			/// </summary>
			public void Clear()
			{
				_datePicker.SelectedDate = null;
			}
			
			/// <summary>
			/// Gets or sets a value indicating that the text-boxes are/should be
			/// read-only.
			/// </summary>
			public bool IsReadOnly
			{
				get
				{
					return !IsEnabled;
				}
				set
				{
					IsEnabled = !value;
				}
			}
		#endregion
	}
}
